<template>
  <div class="btnBox">
    <van-popup :close-on-click-overlay="false" v-model="show.isShow">
      <div
        class="details_content"
        :style="{ background: currentConfig.mainAreaBg }"
      >
        <!-- 头部信息区域 -->
        <div class="top-info">
          <div class="user-header">
            <van-image
              round
              :src="
                playerInfo.imageUrl && playerInfo.imageUrl.trim()
                  ? playerInfo.imageUrl
                  : require('@/assets/list_touxiang.png')
              "
            />
            <div class="user-id">
              {{ playerInfo.activityNum }}号演员--{{ playerInfo.name }}
            </div>
          </div>
          <div
            class="stats-row"
            :style="{
              background: currentConfig.countBg,
              color: currentConfig.count,
            }"
          >
            <div class="stat-item">
              <div class="stat-value">{{ playerInfo.rank }}</div>
              <div class="stat-label">排名</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ playerInfo.voteCount }}</div>
              <div class="stat-label">票数</div>
            </div>
            <!-- <div class="stat-item">
              <div class="stat-value">0</div>
              <div class="stat-label">获得鼓励</div>
            </div> -->
            <div class="stat-item">
              <div class="stat-value">{{ playerInfo.view }}</div>
              <div class="stat-label">浏览量</div>
            </div>
          </div>
        </div>

        <!-- 选手照片区域 -->
        <div class="player-photo-section">
          <div class="section-title">选手照片</div>
          <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
            <van-swipe-item
              v-for="(image, idx) in playerInfo.imageUrl"
              :key="`carousel-${idx}`"
            >
              <div class="carousel-slide">
                <img
                  :src="image"
                  class="slide-image"
                  :alt="`轮播图${idx + 1}`"
                />
              </div>
            </van-swipe-item>
          </van-swipe>
        </div>

        <!-- 票数贡献榜区域 -->
        <div class="contribution-rank-section">
          <div class="section-title">票数贡献榜</div>
          <div class="contribution-content">
            <div class="heart-icon">
              <van-icon name="heart" color="#ff4d4f" size="24" />
              <img
                style="width: 38px; margin: 20px 0px"
                src="@/assets/like.png"
                alt=""
              />
            </div>
            <div class="desc-text">喜欢我的人在这里驻留</div>
            <div class="help-btn" @click="goAddTickets">
              <van-button
                round
                type="info"
                :style="currentConfig.button"
                size="small"
                >帮ta加票</van-button
              >
            </div>
          </div>
        </div>

        <!-- 投票记录区域 -->
        <div class="vote-record-section">
          <div class="section-title">投票记录</div>
          <!-- 滚动容器 -->
          <div class="record-scroll" ref="scrollContainer">
            <van-list
              v-model="loading"
              :finished="finished"
              finished-text="没有更多了"
              @load="onLoad"
              :error.sync="error"
              error-text="请求失败，点击重新加载"
              style="padding-bottom: 20px"
            >
              <!-- 动态加载的记录 -->
              <div
                class="record-item"
                v-for="(item, index) in voteRecords"
                :key="index"
              >
                <div class="record-info">
                  <!-- <div class="nickname">{{ item.nickname }}</div> -->
                  <div class="nickname">{{ item.voterNickname }}</div>
                  <div class="date">{{ item.voteTime }}</div>
                </div>
                <div class="record-count">+{{ item.voteCount }}</div>
              </div>
              <!-- 数据为空时显示 -->
              <!-- <div
                class="empty-tip"
                v-if="voteRecords.length === 0 && !emptyState"
              >
                暂无投票记录
              </div> -->
            </van-list>
          </div>
        </div>
      </div>

      <!-- 底部 -->
      <div class="footer">
        <div class="shouye comBar" @click="closePopue">
          <!-- <span> <img src="@/assets/shouye.png" alt="" /> </span
          ><span class="tetx">首页</span> -->
          <span
            ><van-icon
              name="wap-home-o"
              style="font-size: 16px"
              :style="{ color: currentConfig.navActiveColor }" /></span
          ><span class="tetx" :style="{ color: currentConfig.navActiveColor }"
            >首页</span
          >
        </div>
        <div class="vote-btn" :style="currentConfig.button" @click="handleVote">
          投票
        </div>
        <div class="jiapiao comBar" @click="goAddTickets">
          <span> <img src="@/assets/jiapiao.png" alt="" /> </span
          ><span class="tetx">帮ta加票</span>
        </div>
      </div>

      <!-- 投票成功 -->
      <!-- <van-overlay :show="showSuccess">
        <div class="wrapper" @click.stop>
          <div class="successBlock">


          </div>
        </div>
      </van-overlay> -->
      <!-- 投票成功遮罩层 -->
      <van-overlay :show="showSuccess">
        <div class="wrapper" @click.stop>
          <div class="successBlock">
            <!-- 关闭按钮 -->
            <div class="close-btn" @click="closeSuccessDialog">
              <van-icon name="cross" size="20" color="#999" />
            </div>

            <!-- 成功图标 -->
            <div class="success-icon">
              <van-icon name="passed" color="#67c300" size="60" />
            </div>

            <!-- 标题 -->
            <div class="title">投票成功</div>

            <!-- 选手信息 -->
            <div class="candidate-info">
              <span class="candidate-number"
                >{{ playerInfo.activityNum }}号演员</span
              >
              <span class="candidate-name">{{ playerInfo.name }}</span>
            </div>

            <!-- 票数变化 -->
            <div class="vote-count">+1票</div>

            <!-- 帮ta加票按钮 -->
            <van-button class="add-vote-btn" @click="goAddTickets">
              帮ta加票
            </van-button>
          </div>
        </div>
      </van-overlay>

      <!-- 活动结束 -->
    </van-popup>
  </div>
</template>

<script>
import { mapGetters, mapMutations } from "vuex"; // 引入 Vuex 辅助函数
import heic2any from "heic2any";
import wx from "weixin-js-sdk";
import { Toast } from "vant";
import AddTickets from "../AddTickets.vue"; //加票
import { getVoteing, getVoteRecords } from "@/api/index.js";
export default {
  props: ["childrenData"],
  data() {
    return {
      showSuccess: false, //投票成功
      // 组件显示
      comFlag: true,
      show: {
        isShow: false,
        buttonStyle: "",
        type: 0,
      },
      userLocation: null,
      signUpForm: {
        name: "",
        phone: "",
        declaration: "",
      },
      form: {
        tbTestimonials: "",
        tbLongitudeLatitude: "",
        tbLocation: "",
        tbUserid: localStorage.getItem("uuid"),
      },
      showCalender: false,
      PhotoLoading: false,
      minDate: new Date(2025, 0, 1),
      maxDate: new Date(2099, 10, 1),
      currentDate: new Date(),
      wxId: localStorage.getItem("uuid"),
      fileList: [],
      ShowSubMit: false,
      playerInfo: {}, // 新增：存储选手详情（从childrenData同步）
      currentConfig: {}, //样式
      id: "",
      // 投票记录原始数据（模拟，实际需接口返回）
      voteRecords: [], // 空数组，无初始数据
      page: {
        page: 1,
        pageSize: 10,
      },
      total: 0, // 总数据条数（从接口获取）

      loading: false,
      finished: false,
      error: false, //提示错误信息
      emptyState: false, //初始空状态

      isLoading: false, // 是否加载中
      hasMoreData: true, // 是否有更多数据
    };
  },
  computed: {
    // 当前显示的记录（根据页码截取）
  },
  mounted() {
    // 1. 优先从 localStorage 获取数据（页面刷新后不丢失）
    this.activityId =
      localStorage.getItem("vote_activityId") || this.sharedData.activityId;
    this.templateId =
      Number(localStorage.getItem("vote_templateId")) ||
      this.sharedData.templateId;

    // 2. 验证数据有效性
    if (!this.activityId) {
      Toast.fail("未获取到活动ID");
      return;
    }

    // this.getRecordsList();
    // this.currentConfig;
    // console.log("🚀 ~ mounted ~ this.currentConfig:", this.currentConfig);
  },
  watch: {
    childrenData: {
      deep: true,
      handler(newVal) {
        if (newVal) {
          this.show.isShow = newVal.show;
          this.playerInfo = newVal.playerItem || {};
          this.currentConfig = newVal.passCurrentConfig || {};

          console.log("🚀 ~ handler newVal:", newVal);
        }
      },
    },
    // 新增：监听 playerInfo.id 的变化
    "playerInfo.id": {
      handler(newId, oldId) {
        // 当 ID 有效且与旧值不同时，重新加载记录
        if (newId && newId !== oldId) {
          this.page.page = 1; // 重置为第 1 页
          this.voteRecords = []; // 清空旧记录
          this.finished = false; // 标记为“有更多数据”，允许重新加载
          this.getRecordsList(); // 调用接口
        }
      },
      immediate: true, // 初始化时立即执行一次（确保首次加载也触发）
    },
  },
  methods: {
    onLoad() {
      this.loading = true; //加载数据
      this.getRecordsList(); // 请求后端数据铺设界面
    },
    // 记录列表
    async getRecordsList() {
      this.loading = true; // 开始加载
      await getVoteRecords(this.playerInfo.id, this.page)
        .then((res) => {
          console.log("投票记录接口响应:", res);
          if (res.data.code == 0) {
            const newList = res.data.data.records || [];
            // 拼接新数据（因 page 已重置为 1，首次会覆盖旧数据）
            this.voteRecords = this.voteRecords.concat(newList);
            this.loading = false; // 结束加载
            // 判断是否还有更多数据（若返回条数小于页大小，说明无更多）
            this.finished = newList.length < this.page.pageSize;
            // 有数据时，页码+1 用于下一次加载
            if (newList.length > 0) {
              this.page.page++;
            }
          } else {
            this.finished = true; // 接口返回错误，标记为“无更多数据”
            this.loading = false;
          }
        })
        .catch((error) => {
          console.error("获取投票记录失败:", error);
          this.error = true; // 显示错误提示
          this.emptyState = true; // 标记为“空状态”
          this.loading = false;
        });
    },
    // 点击“投票”按钮：模拟投票逻辑（实际需调用接口）
    // handleVote() {
    //   // 这里可替换为真实接口调用，成功后再打开弹窗
    //   // 示例直接打开弹窗
    //   this.showSuccess = true;
    // },
    // 点击“投票”按钮：调用 getVoteing 接口
    async handleVote() {
      // 1. 加载提示：防止重复点击
      this.$toast.loading({
        message: "投票中...",
        forbidClick: true,
        duration: 0,
      });

      try {
        // 2. 组装接口所需 JSON 参数
        const voteParams = {
          participantId: this.playerInfo.id, // 选手ID（从 playerInfo 中获取）
          voterOpenId: localStorage.getItem("openId") || "", // 投票人ID（从本地存储获取）
          voteCount: 1, // 票数固定为 1（按需求）
          voteType: "free", // 投票类型固定为 free（按需求）
        };

        // 3. 参数有效性校验（避免接口调用失败）
        if (!voteParams.participantId) {
          this.$toast.fail("未获取到选手信息，无法投票");
          return;
        }
        if (!voteParams.voterOpenId) {
          this.$toast.fail("未获取到用户信息，请重新进入页面");
          return;
        }

        // 4. 调用 getVoteing 接口（传递 JSON 参数）
        const response = await getVoteing(voteParams);
        console.log("投票接口响应:", response);

        // 5. 接口成功处理
        if (response.data?.code == 0) {
          // 5.1 提示投票成功
          this.$toast.success("投票成功！");
          // 5.2 更新选手票数（本地实时刷新，无需等列表重新加载）
          this.playerInfo.voteCount = (this.playerInfo.voteCount || 0) + 1;
          // 5.3 打开投票成功弹窗
          this.showSuccess = true;
          // 5.4 重新加载投票记录，显示最新投票
          this.page.page = 1;
          this.voteRecords = [];
          this.getRecordsList();
        } else {
          console.log("已用完");

          this.$toast.fail({
            message: response.data?.msg || "投票失败，请重试",
            duration: 2000,
          });
          // 6. 接口失败处理（提示后端返回的错误信息）
          // this.$toast.fail(response.data?.msg || "投票失败，请重试");
        }
      } catch (error) {
        // 7. 异常处理（如网络错误）
        console.error("投票接口调用失败:", error);
        this.$toast.fail("网络异常，投票失败");
      } finally {
        // 8. 无论成功/失败，关闭加载提示
        this.$toast.clear();
      }
    },
    // 关闭投票成功弹窗
    closeSuccessDialog() {
      this.showSuccess = false;
    },
    // 帮ta加票逻辑
    goAddTickets() {
      this.show.isShow = false;
      this.$emit("add-event", this.show,this.playerInfo); // 触发父组件事件（如果需要）
      this.closeSuccessDialog(); // 关闭成功弹窗
    },
    ...mapMutations("tabBar", ["SET_ACTIVE_INDEX"]),
    // 关闭主弹窗逻辑
    closePopue() {
      this.show.isShow = false;
      this.$emit("child-event", this.show); // 触发父组件事件（如果需要）
      this.$router.push("/");
      const pathMap = {
        "/": 0,
        "/ranking": 1,
        "/activity": 2,
        "/search": 3,
      };
      const targetIndex = pathMap[this.$route.path] || 0;
      this.SET_ACTIVE_INDEX(targetIndex);
    },
    showPerPopup() {
      this.passPerData = {
        show: true,
        buttonStyle: this.buttonStyle, // 将父组件的buttonStyle传递给子组件
      };
    },
  },
};
</script>

<style scoped lang="less">
.van-icon {
  font-size: 20px;
  margin-right: 3px;
}
.van-popup {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}

.title {
  color: #666;
}

.icon {
  color: #666;
  font-size: 18px;
}

::v-deep .van-image {
  display: block;
  width: 100px;
  height: 100px;
  overflow: hidden;
}

::v-deep .van-uploader__wrapper {
  width: 100%;
}

::v-deep .van-uploader__upload {
  width: 100px;
  height: 100px;
}

::v-deep .van-uploader__preview,
.van-uploader__upload {
  margin: 0 6px 6px 0;
}

::v-deep .van-cell--clickable {
  margin-top: 25px;
  border: 1px solid #eceaea;
}

.location {
  color: #666;
  font-size: 16px;
  margin: 10px 0px 0px 20px;
}

.dateClass {
  border-bottom: 1px solid #f4f4f4;
}

::v-deep .van-cell__value {
  text-align: left;
}

::v-deep .van-cell__title,
.van-cell__value {
  -webkit-box-flex: 1;
  /* -webkit-flex: 1; */
  /* flex: 1; */
}

::v-deep .van-uploader__file {
  width: 100px;
  height: 100px;
}

.locationBer {
  width: 70%;
}

.dataBer {
  height: 32px;
  line-height: 32px;
  margin-right: 18px;
}

::v-deep .van-cell {
  color: #323233 !important;
  background-color: #fff !important;
}

.details_content {
  /* height: 900px; */
  flex: 1;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  padding-bottom: 70px;
}
.details_box {
  width: 100%;
  height: 300px;
  border: 1px solid #000;
}

/* 头部信息区域 */
.top-info {
  padding: 10px;
  .user-header {
    display: flex;
    flex-direction: column;
    align-items: center;
    .user-id {
      margin: 0 10px;
      font-size: 14px;
      color: #333;
    }
  }
  .stats-row {
    display: flex;
    justify-content: space-around;
    // background-color: #07c160;
    // color: #fff;
    border-radius: 8px;
    margin-top: 10px;
    padding: 8px 0;
    .stat-item {
      text-align: center;
      .stat-value {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 4px;
      }
      .stat-label {
        font-size: 12px;
      }
    }
  }
}

/* 选手照片区域 */
.player-photo-section {
  border-radius: 8px;
  padding: 10px 10px 20px 10px;
  margin: 10px;
  background-color: #fff;
  min-height: 200px;
  .section-title {
    font-size: 16px;
    font-weight: bold;
    color: #738593;
    margin-bottom: 8px;
    text-align: center;
  }
  /deep/ .van-image {
    border-radius: 8px;
  }
}

/* 票数贡献榜区域 */
.contribution-rank-section {
  border-radius: 8px;
  padding: 10px;
  margin: 10px;
  background-color: #fff;
  .section-title {
    font-size: 16px;
    font-weight: bold;
    color: #738593;
    margin-bottom: 12px;
    text-align: center;
  }
  .contribution-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    .heart-icon {
      display: flex;
      align-items: center;
      margin-bottom: 8px;
      .icon-text {
        font-size: 14px;
        color: #999;
        margin-left: 5px;
      }
    }
    .help-btn {
      margin-bottom: 8px;
    }
    .desc-text {
      font-size: 12px;
      color: #999;
      margin-bottom: 10px;
    }
  }
}

/* 投票记录区域 */
/* 投票记录区域样式 */
.vote-record-section {
  border-radius: 8px;
  padding: 10px;
  margin: 10px;
  background-color: #fff;

  .section-title {
    font-size: 16px;
    font-weight: bold;
    color: #738593;
    margin-bottom: 12px;
    text-align: center;
  }

  .record-scroll {
    max-height: 200px; /* 固定高度，超出滚动 */
    overflow-y: auto;
    -webkit-overflow-scrolling: touch; /* 优化移动端滚动 */
    padding-bottom: 1px;
  }

  .record-item {
    display: flex;
    // flex-direction: column;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #f5f5f5;

    .record-info {
      .nickname {
        color: #333;
        font-size: 14px;
        margin-right: 10px;
      }
      .date {
        color: #999;
        font-size: 12px;
      }
    }
    .record-count {
      color: #07c160;
      font-size: 14px;
      font-weight: 500;
    }
  }

  /* 空状态提示 */
  .empty-tip {
    text-align: center;
    padding: 30px 0;
    color: #999;
    font-size: 14px;
  }

  /* 加载中提示 */
  .loading {
    text-align: center;
    padding: 15px 0;
    color: #999;
    font-size: 12px;
  }

  /* 无更多提示 */
  .no-more {
    text-align: center;
    padding: 10px 0;
    color: #999;
    font-size: 12px;
    border-top: 1px solid #f5f5f5;
    margin-top: 5px;
  }
}
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  display: flex;
  z-index: 100;
  justify-content: space-between;
  align-items: center;
  padding: 0px 10px;
  .comBar {
    font-weight: 500;
    font-size: 16px;
    span {
      display: inline-block;
      height: 30px;
      line-height: 30px;
    }
    .tetx {
      margin: 15px 0px 15px 0px;
    }
  }
  .shouye {
    img {
      width: 23px;
      margin-right: 5px;
    }
  }
  .vote-btn {
    position: absolute;
    left: 50%;
    top: -30px;
    transform: translateX(-50%);
    width: 60px;
    height: 60px;
    line-height: 60px;
    text-align: center;
    // background-color: #07c160;
    // color: #fff;
    border-radius: 50%;
    font-size: 16px;
    font-weight: 600;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
    &:active {
      opacity: 0.8;
    }
  }
  .jiapiao {
    img {
      width: 34px;
      margin: 13px 0px;
    }
  }
}
::v-deep .van-image {
  width: 80px;
  height: 80px;
  margin: 10px 0px;
}

::v-deep .van-button--small {
  height: 32px;
  padding: 0 100px;
  font-size: 12px;
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
::v-deep .van-overlay {
  z-index: 1000;
  height: 100vh;
}
/* 投票成功弹窗样式 */
.wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
}

.successBlock {
  width: 70%;
  max-width: 300px;
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  text-align: center;
  position: relative;
}

.close-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  cursor: pointer;
}

.success-icon {
  margin-bottom: 16px;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.candidate-info {
  font-size: 16px;
  color: #666;
  margin-bottom: 12px;
}

.candidate-number {
  color: #999;
}

.vote-count {
  font-size: 16px;
  color: #ff4d4f;
  margin-bottom: 3px;
}

.add-vote-btn {
  width: 90%;
  background-color: #07c160;
  color: #fff;
}
</style>
